<?php

    class LoginController extends Application {
        
        function setup()
        {
            $this->actions = array('index','logout','forgot_password');
            $this->before_filter('bypass_login');
        }
        
        function bypass_login()
        {            
            if ( $this->action != 'logout' && $this->is_logged_in($redirect=false) )
            {
                $this->redirect_to(array('controller'=>'admin/dashboard'));
            }
        }
        
		function index() // login
		{
		    if ( $_POST )
		    {
		        if ( $this->login_user() )
		        {
		            // redirect them to where they want to go
                    if ( !empty($_POST['login_referrer']) )
                    {
                       $this->redirect_to($_POST['login_referrer']);
                    } else {                       
                       $this->redirect_to(array('controller'=>'admin/dashboard'));
                    }
		        } else {
		            flash('error','Username or Password Incorrect');
		        }
		    }
		    $this->assign('login_referrer',$_SESSION['login_referrer']);
		}


		function logout() 
		{
		    $this->use_layout(false);
		    $this->logout_user();
		    $this->redirect_to('index');
		}

        // do forgot password crap
		function forgot_password() 
		{
		    if ( $_POST )
		    {
		        use_model('users');
		        $u = new Users();
		        if ( $u->send_user_password($_POST) ) {
		            flash('notice','Your login details have been sent.');
		            $this->redirect_to('index');
	            } else {
	                flash('error','Sorry, we were not able to access your account. You can try again or contact your administrator.');
	            }
		    }		    		    
		}
		
		function login_user()
        {
            use_model('users');
            $u = new Users();
                        
            $authed_user = $u->authenticate($_POST);
            if ( $authed_user )
            {
                session_regenerate_id();
                $_SESSION['user_id'] = $authed_user;
                
                $user_id = $authed_user;
                use_pixel_lib('class.cookie.php');
                $cookie = new clsCookie('pixelapp');
                $cookie->expire = 86400 * 14;
                $cookie->init();
                $secret_pass = create_hash('user_pass'.COOKIECRYPTKEY.$_SERVER['REMOTE_ADDR']);
                $secret_user = create_hash('user_login'.COOKIECRYPTKEY.$_SERVER['REMOTE_ADDR']);
                $user_pass   = create_hash($_POST['user_password']);
                $cookie->aValues[$secret_pass] = create_hash(COOKIECRYPTKEY.$user_pass);
                $cookie->aValues[$secret_user] = rawurlencode($_POST['user_login']);
                $cookie->send();
                
                return true;               
           } else {
               return false;
           }
        }    
    }

?>